﻿using Dao.User;
using ShareCode.Entity.User;
using Infrastructure.Attributes.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Attributes;
using System.Reflection;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Mvc;

namespace Bll.User
{
    /// <summary>
    /// by zhouxin
    ///</summary>
    [Component]
    public class UserApiBll : BaseTreeBll<UserApiEntity>
    {
        protected override UserApiDao? Dao => (UserApiDao?)base.Dao;

        [Autowired]
        public UserApiDao SetDao { set { this._Dao = value; } }


        public async void InitAPI(Type type, AuthAttribute auth)
        {
            var route = type.GetCustomAttribute<RouteAttribute>();
            if (route == default) return;

            var routes = route.Template.Split('/').ToList();
            routes.RemoveAt(routes.Count - 1);

            string className = type.Name.Replace("Controller", "");
            routes.Add(className);

            UserApiEntity pmodel = new UserApiEntity();
            foreach (var item in routes)
            {
                pmodel = await Dao!.InsertPath(item, item, pmodel.Id, pmodel.TreeRootId);
            }

            if (pmodel.Id > 0)
            {
                //删除以前添加过的接口
                await Dao!.DeleteAsync(t => t.TreeParentId == pmodel.Id);
            }

            var methods = type.GetMethods();

            foreach (var method in methods)
            {
                var _auth = method.GetCustomAttribute<AuthAttribute>();

                if (_auth == default) continue;

                await Dao!.InsertAPI(method.Name, _auth.Desc, (_auth.SerialNumber + auth.SerialNumber*1000).ToString(), pmodel.Id, pmodel.TreeRootId);

            }

        }
    }
}
